const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const paramSerialize = data => {
  let url = '';
  for (const k in data) {
    const value = (data[k] !== undefined && data[k] !== null) ? data[k] : '';
    url += `&${k}=${encodeURIComponent(value)}`;
  }
  return url ? url.substring(1) : '';
};

/*
     * 获取查询字符串
     * params string key
     * params string url
     */
function getUrlParams(url) {
  const Params = {}
  if (url.indexOf('?') > 0) {//判断是否有qurey
    let parmas = url.slice(url.indexOf('?') + 1)//截取出query
    const paramlists = parmas.split('&')//分割键值对
    for (const param of paramlists) {
      let a = param.split('=')
      Object.assign(Params, { [a[0]]: a[1] })//将键值对封装成对象
    }
  }
  return Params
}

function groupBy(array, key) {
  if(array instanceof Array){
    return array.reduce((result, currentItem) => {
      // 使用 key 函数获取分组的键
      const groupKey = key(currentItem);
  
      // 确保 result 对象中有对应键的数组
      if (!result[groupKey]) {
        result[groupKey] = [];
      }
  
      // 将当前项添加到对应的数组中
      result[groupKey].push(currentItem);
  
      return result;
    }, {});
  }
}

function htmlEncode(str){  
  var s = str;
  if(str&&typeof(str) == "string"){
    // s = str.replace(/&/g,"&amp;");
    s = s.replace(/</g,"&lt;");
    s = s.replace(/>/g,"&gt;");
    // s = s.replace(/ /g,"&nbsp;");
    s = s.replace(/\'/g,"&#39;");
    s = s.replace(/\"/g,"&quot;");
    str = s
  }
  return str;  
 
}

function checkInputCode(str){
  const validCode = ['<','>','&'];
  if(str&&typeof(str) == "string"){
    for (var i = 0; i < str.length; i++) {
      if (validCode.includes(str[i])) {
        return true;
      }
    }
  
  }
  return false;
}

function htmlDecode(str){  
  var s = "";
  if(str&&typeof(str) == "string"){
    s = str.replace(/&amp;/g,"&");
    s = s.replace(/&lt;/g,"<");
    s = s.replace(/&gt;/g,">");
    s = s.replace(/&nbsp;/g," ");
    s = s.replace(/&#39;/g,"\'");
    s = s.replace(/&quot;/g,"\"");
    str = s 
  }
  return str;  
}

function checkImageSafe(url) {
  return new Promise(resolve=>{
  var img = wx.createImage();
  img.onload = function() {
    resolve(true); // 图片加载成功，视为安全
  };
  img.onerror = function() {
    resolve(false); // 图片加载失败，视为不安全
  };
  img.src = url; // 设置图片的URL来开始加载
})
}

//防抖
function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
      gapTime = 1500
  }

  let _lastTime = null

  // 返回新的函数
  return function () {
      let _nowTime = + new Date()
      if (_nowTime - _lastTime > gapTime || !_lastTime) {
          fn.apply(this, arguments)   //将this和参数传给原函数
          _lastTime = _nowTime
      }
  }
}



module.exports = {
  formatTime,
  paramSerialize,
  getUrlParams,
  groupBy,
  htmlEncode,
  htmlDecode,
  checkInputCode,
  checkImageSafe,
  throttle
}
